package be.bonamis.umpire.quiz;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import be.bonamis.umpire.business.config.DataSourceConfiguration;
import be.bonamis.umpire.business.config.UmpireConfig;

@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("default")
@ContextConfiguration(classes = { UmpireConfig.class })
public class QuizServiceEmptyDB {
	
	@Autowired
	private DataSourceConfiguration dataSourceConfiguration;

	@Before
	public void init() throws Exception {		
		dropTable();		
	}

	@Test
	@Ignore
	public void testSimple() throws IOException {
		System.out.println("Done");
	}	
	
	private void dropTable() throws Exception {
		List<String> list = new ArrayList<String>();

		list.add("personquiz_responses");
		list.add("question_answer");
		list.add("quiz_question");
		list.add("personquiz ");
		list.add("question ");
		list.add("quiz ");
		list.add("answer");

		for (String string : list) {
			String sql = "DROP TABLE "+ string;
			executeSql(sql);
		}		
	}

	private void executeSql(String sql) throws Exception {
		Connection conn = null;
		try {
			conn = dataSourceConfiguration.dataSource().getConnection();
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.executeUpdate();
			ps.close();

		} catch (SQLException e) {
			throw new RuntimeException(e);

		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
				}
			}
		}
	}
}
